<template>
  <div>
    <el-form ref="form" :model="form" label-width="80px">
      <div class="formUser">
        <el-form-item label="头像">
          <div class="unlodBox">
            <el-upload
              class="upload-demo"
              action
              :http-request="uploadFiles"
              ref="upload"
              :limit="fileLimit"
              :on-remove="handleRemove"
              :file-list="fileList"
              :on-exceed="handleExceed"
              :before-upload="beforeUpload"
              :show-file-list="false"
              :headers="headers"
              :on-change="fileChange1"
            >
              <el-image
                v-if="imageUrl"
                class="imageGood"
                :src="imageUrl"
                style="width: 360px; height: 180px"
              ></el-image>
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过5M
              </div>
            </el-upload>
          </div>
        </el-form-item>
      </div>
    </el-form>
    <!-- ===================================================== -->
    <!-- <el-upload
      action="#"
      multiple
      accept="image/jpg,image/jpeg,image/png"
      list-type="picture-card"
      :on-change="fileChange"
      :auto-upload="false"
    >
    </el-upload> -->
    <!-- <el-button type="primary" @click="compressFile">压缩</el-button> -->
    <el-button type="primary" @click="compressFile1">压缩1</el-button>
    <div>
      <el-image
        v-for="(item, index) in imageList"
        :key="index"
        fit="cover"
        style="width: 300px; height: 300px"
        :src="item.fileBinary.blobUrl"
        :preview-src-list="srcList"
      ></el-image>
    </div>
  </div>
</template>
 
<script>
import { compressImage } from "../../../assets/js/compressImage";
import { uploadFiles } from "../../../utils/api";
export default {
  data() {
    return {
      fileList: [],
      imageList: [],
      srcList: [],
      srcList2: {},
      //上传图片
      imageUrl: "",
      imageUrl1: "",
      fileList1: [],
      fileType: ["png", "jpg", "jpeg"],
      fileLimit: 1,
      headers: { "Content-Type": "multipart/form-data" },
      form: {},
      imageBase: "",
    };
  },
  methods: {
    //超出文件个数的回调
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    handleRemove() {},
    //这是我自定义的移除事件
    handleClosedelete(i) {
      this.fileList.splice(i, 1); //删除上传的文件
    },
    //上传文件的格式
    beforeUpload(file) {
      if (file.type != "" || file.type != null || file.type != undefined) {
        //截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, "").toLowerCase();
        //计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 1; //这里做文件大小限制
        //如果大于50M
        if (!isLt5M) {
          this.$message.error("上传文件大小不能超过 1MB!");
          return false;
        }
        //如果文件类型不在允许上传的范围内
        if (this.fileType.includes(FileExt)) {
          return true;
        } else {
          this.$message.error("上传文件格式不正确!");
          return false;
        }
      }
    },

    //上传文件的事件
    uploadFiles(item) {
      this.$message("文件上传中........");
      //上传文件的需要formdata类型;所以要转
      console.log("item", item);
      this.compressFile1();
      let timer = setTimeout(() => {
        console.log("this.srcList3", this.srcList2);
        uploadFiles(this.srcList2).then((res) => {
          if (res.data.status != false || res.data.id != null) {
            res.data.data.saveurl; //半截
            res.data.data.weburl; //全拼
            this.imageUrl = res.data.data.weburl;
            this.imageUrl1 = res.data.data.saveurl;
            this.fileList.push(this.srcList2); //成功过后手动将文件添加到展示列表里
            let i = this.fileList.indexOf(this.srcList2);
            this.handleSuccess();
          }
        });
        clearTimeout(timer);
      }, 1000);
    },
    //上传成功后的回调
    handleSuccess() {
      this.$message({
        message: "上传成功",
        type: "success",
      });
      this.handleClosedelete();
    },

    fileChange1(file, fileList) {
      this.fileList = fileList;
    },
    compressFile1() {
      let config = {
        quality: 0.5, //默认0.5  0-1
        // width:100,
        // height:100
      };
      this.fileList.forEach(async (item) => {
        // console.log("this.fileList1", this.fileList1);
        console.log("原图size1===>", item.size);
        let result = await compressImage({
          file: item.raw,
          config,
          fileName: item.name,
        });
        console.log("压缩后图片size1===>", result.finalFile.size);
        // this.imageList.push(result);
        this.srcList.push(result.fileBinary.blobUrl);
        this.srcList2 = result.finalFile;
        // console.log("aaa", result.finalFile);
        // console.log("bbb", this.srcList2);
        console.log("this.srcList", this.srcList);
      });
      console.log("压缩后图片1===>", this.imageList);
    },

    // ===================================================
    // fileChange(file, fileList) {
    //   this.fileList = fileList;
    // },
    // compressFile() {
    //   let config = {
    //     quality: 0.5, //默认0.5  0-1
    //     // width:100,
    //     // height:100
    //   };
    //   this.fileList.forEach(async (item) => {
    //     console.log("this.fileList", this.fileList);
    //     console.log("原图size===>", item.size);
    //     let result = await compressImage({
    //       file: item.raw,
    //       config,
    //       fileName: item.name,
    //     });
    //     console.log("压缩后图片size===>", result.finalFile.file.size);
    //     this.imageList.push(result);
    //     this.srcList.push(result.fileBinary.blobUrl);
    //   });
    //   console.log("压缩后图片===>", this.imageList);
    // },
  },
};
</script>